package com.taoyige.common;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.system.text.ShortMessage;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;

import com.taoyige.AppConfig;
import com.taoyige.AppException;
import com.taoyige.AppManager;
import com.taoyige.R;
import com.taoyige.api.ApiClient;
import com.taoyige.bean.Address;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.ui.AddAddressActivity;
import com.taoyige.ui.AddressDetailActivity;
import com.taoyige.ui.AllOrdersActivity;
import com.taoyige.ui.BuyNowActivity;
import com.taoyige.ui.GoodsDetailActivity;
import com.taoyige.ui.MainActivity;
import com.taoyige.ui.NotReceiptOrdersActivity;
import com.taoyige.ui.OrderDetailActivity;
import com.taoyige.ui.OrdersStatusActivity;
import com.taoyige.ui.UnpaidOrdersActivity;
import com.taoyige.ui.UserActivity;
import com.taoyige.ui.UserLoginActivity;

/**
 * 应用程序UI工具包：封装UI相关的一些操作
 * 
 * @author peter
 * @version 1.0
 * @created 2014-11-12
 */
public class UIHelper {
	private final static String TAG = "UIHelper";
	
	public final static int LISTVIEW_ACTION_INIT = 0x01;
	public final static int LISTVIEW_ACTION_REFRESH = 0x02;
	public final static int LISTVIEW_ACTION_SCROLL = 0x03;
	public final static int LISTVIEW_ACTION_CHANGE_CATALOG = 0x04;

	public final static int LISTVIEW_DATA_MORE = 0x01;
	public final static int LISTVIEW_DATA_LOADING = 0x02;
	public final static int LISTVIEW_DATA_FULL = 0x03;
	public final static int LISTVIEW_DATA_EMPTY = 0x04;

	
	public final static int LISTVIEW_DATATYPE_ORDER = 0x01;
	
	public final static int REQUEST_CODE_FOR_RESULT = 0x01;
	public final static int REQUEST_CODE_FOR_REPLY = 0x02;

/**
	 * 显示首页
	 * 
	 * @param activity
	 */
	/*
	public static void showHome(Activity activity) {
		Intent intent = new Intent(activity, Main.class);
		activity.startActivity(intent);
		activity.finish();
	}*/

	/**
	 * 显示登录页面
	 * 
	 * @param activity
	 */
	/*
	public static void showLoginDialog(Context context) {
		Intent intent = new Intent(context, LoginDialog.class);
		if (context instanceof Main)
			intent.putExtra("LOGINTYPE", LoginDialog.LOGIN_MAIN);
		else if (context instanceof Setting)
			intent.putExtra("LOGINTYPE", LoginDialog.LOGIN_SETTING);
		else
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}*/

	
	/**
	 * 显示首页
	 * 
	 * @param context
	 * @param goodsId
	 */
	public static void showIndex(Context context) {
		Intent intent = new Intent(context, MainActivity.class);
		context.startActivity(intent);
	}
	

	/**
	 * 显示商品详情页
	 * 
	 * @param context
	 * @param goodsId
	 */
	public static void showGoodsDetail(Context context, String goodsId) {
		Intent intent = new Intent(context, GoodsDetailActivity.class);
		intent.putExtra("goodsId", goodsId);
		context.startActivity(intent);
	}
	
	/**
	 * 显示商品详情页
	 * 
	 * @param context
	 * @param goodsId
	 */
	public static void showGoodsCommingsoonDetail(Context context, Long goodsId) {
		Intent intent = new Intent(context, GoodsDetailActivity.class);
		intent.putExtra("goodsId", goodsId);
		intent.putExtra("status", 1);
		context.startActivity(intent);
	}
	

	/**
	 * 显示用户登陆界面
	 * 
	 * @param context
	 * @param loginType
	 */
	public static void showUserLogin(Context context,int loginType) {
		Intent intent = new Intent(context, UserLoginActivity.class);
		intent.putExtra(AppConfig.LOGIN_TYPE, loginType);
		context.startActivity(intent);
	}
	
	
	/**
	 * 显示用户中心带BadgeView
	 * @param 
	 * @param context
	 */
	public static void showUserCenter(Context context,Integer badgeFlag) {
		Intent intent = new Intent(context, UserActivity.class);
		intent.putExtra("badgeFlag",badgeFlag);
		context.startActivity(intent);
	}

	
	public static void showOrderDetail(Context context,String orderId,String uid) {
		Intent intent = new Intent(context, OrderDetailActivity.class);
		intent.putExtra("orderId", orderId);
		intent.putExtra("uid", uid);
		context.startActivity(intent);
	}
	
	
	public static void showOrderTrack(Context context,String orderId,String uid) {
		Intent intent = new Intent(context, OrdersStatusActivity.class);
		intent.putExtra("orderId", orderId);
		intent.putExtra("uid", uid);
		context.startActivity(intent);
	}
	public static void showOrderStatus(Context context,String orderId,String uid) {
		Intent intent = new Intent(context, OrdersStatusActivity.class);
		intent.putExtra("orderId", orderId);
		intent.putExtra("uid", uid);
		context.startActivity(intent);
	}
	public static void showUser(Context context) {
		Intent intent = new Intent(context, UserActivity.class);
		context.startActivity(intent);
	}
	public static void showHomePage(Context context) {
		Intent intent = new Intent(context, MainActivity.class);
		context.startActivity(intent);
	}
	public static void showUnpaidOrder(Context context) {
		Intent intent = new Intent(context, UnpaidOrdersActivity.class);
		context.startActivity(intent);
	}
	public static void showNotReceiptOrder(Context context) {
		Intent intent = new Intent(context, NotReceiptOrdersActivity.class);
		context.startActivity(intent);
	}
	public static void showAllOrder(Context context) {
		Intent intent = new Intent(context, AllOrdersActivity.class);
		context.startActivity(intent);
	}
	public static void showAddAddress(Context context,String userId,Order order) {
		Intent intent = new Intent(context, AddAddressActivity.class);
		Address address = new Address();
		address.setId("-1");address.setUserID(userId);
		intent.putExtra("address", address);
		intent.putExtra("order", order);
		context.startActivity(intent);
	}
	public static void showBuyNow(Context context,Order o,int status) {
		Intent intent = new Intent(context, BuyNowActivity.class);
		intent.putExtra("order", o);
		Address address=new Address();
		address.setId("-1");
		intent.putExtra("address", address);
		intent.putExtra("status", status);
		context.startActivity(intent);
	}
	public static void showAddressDetail(Context context,Order o) {
			Intent intent = new Intent(context, AddressDetailActivity.class);
			intent.putExtra("order", o);
			context.startActivity(intent);
	}
	/**
	 * 加载商品图片
	 * 
	 * @param imgFace
	 * @param faceURL
	 */
	public static void showGoodsImage(final ImageView image,final String imageUrl) {
		showLoadImage(image, imageUrl,image.getContext().getString(R.string.msg_load_image_fail));
	}

	/**
	 * 加载显示图片
	 * 
	 * @param imgFace
	 * @param faceURL
	 * @param errMsg
	 */
	public static void showLoadImage(final ImageView imgView,
			final String imgURL, final String errMsg) {
		// 读取本地图片
		if (StringUtils.isEmpty(imgURL)) {
			Bitmap bmp = BitmapFactory.decodeResource(imgView.getResources(),
					R.drawable.demo_goods);
			imgView.setImageBitmap(bmp);
			return;
		}

		// 是否有缓存图片
		final String filename = FileUtils.getFileName(imgURL);
		// Environment.getExternalStorageDirectory();返回/sdcard
		String filepath = imgView.getContext().getFilesDir() + File.separator+ filename;
		File file = new File(filepath);
		if (file.exists()) {
			Bitmap bmp = ImageUtils.getBitmap(imgView.getContext(), filename);
			imgView.setImageBitmap(bmp);
			return;
		}

		// 从网络获取&写入图片缓存
		String _errMsg = imgView.getContext().getString(
				R.string.msg_load_image_fail);
		if (!StringUtils.isEmpty(errMsg))
			_errMsg = errMsg;
		final String ErrMsg = _errMsg;
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 && msg.obj != null) {
					imgView.setImageBitmap((Bitmap) msg.obj);
					try {
						// 写图片缓存
						ImageUtils.saveImage(imgView.getContext(), filename,(Bitmap) msg.obj);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					ToastMessage(imgView.getContext(), ErrMsg);
				}
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Bitmap bmp = ApiClient.getNetBitmap(imgURL);
					msg.what = 1;
					msg.obj = bmp;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	/**
	 * 加载显示图片
	 * 
	 * @param imgFace
	 * @param faceURL
	 * @param errMsg
	 */
	public static void showLoadImageFromSD(final ImageView imgView,
			final String imgURL, final String errMsg) {
		// 读取本地图片
		if (StringUtils.isEmpty(imgURL)) {
			Bitmap bmp = BitmapFactory.decodeResource(imgView.getResources(),
					R.drawable.demo_goods);
			imgView.setImageBitmap(bmp);
			return;
		}

		// 是否有缓存图片
		final String filename = FileUtils.getFileName(imgURL);
		final String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/taoyige/Images/" + filename;
		File file = new File(filepath);
		if (file.exists()) {
			Bitmap bmp = ImageUtils.getBitmapByPath(filepath);
			imgView.setImageBitmap(bmp);
			return;
		}

		// 从网络获取&写入图片缓存
		String _errMsg = imgView.getContext().getString(
				R.string.msg_load_image_fail);
		if (!StringUtils.isEmpty(errMsg))
			_errMsg = errMsg;
		final String ErrMsg = _errMsg;
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1 && msg.obj != null) {
					imgView.setImageBitmap((Bitmap) msg.obj);
					try {
						// 写图片缓存
						ImageUtils.saveImageToSD(imgView.getContext(), filepath, (Bitmap) msg.obj);
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					ToastMessage(imgView.getContext(), ErrMsg);
				}
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					Bitmap bmp = ApiClient.getNetBitmap(imgURL);
					msg.what = 1;
					msg.obj = bmp;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	/**
	 * 弹出Toast消息
	 * 
	 * @param msg
	 */
	public static void ToastMessage(Context cont, String msg) {
		Toast.makeText(cont, msg, Toast.LENGTH_SHORT).show();
	}

	public static void ToastMessage(Context cont, int msg) {
		Toast.makeText(cont, msg, Toast.LENGTH_SHORT).show();
	}

	public static void ToastMessage(Context cont, String msg, int time) {
		Toast.makeText(cont, msg, time).show();
	}
	
	/**
	 * 发送App异常崩溃报告
	 * 
	 * @param cont
	 * @param crashReport
	 */
	public static void sendAppCrashReport(final Context cont,
			final String crashReport) {
		AlertDialog.Builder builder = new AlertDialog.Builder(cont);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(R.string.app_error);
		builder.setMessage(R.string.app_error_message);
		builder.setPositiveButton(R.string.submit_report,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 发送异常报告
						Intent i = new Intent(Intent.ACTION_SEND);
						// i.setType("text/plain"); //模拟器
						i.setType("message/rfc822"); // 真机
						i.putExtra(Intent.EXTRA_EMAIL,
								new String[] { "shenhui@instreet.cn" });
						i.putExtra(Intent.EXTRA_SUBJECT,
								"淘一个Android-APP - 错误报告");
						i.putExtra(Intent.EXTRA_TEXT, crashReport);
						cont.startActivity(Intent.createChooser(i, "发送错误报告"));
						// 退出
						AppManager.getAppManager().appExit(cont);
					}
				});
		builder.setNegativeButton(R.string.sure,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 退出
						AppManager.getAppManager().appExit(cont);
					}
				});
		builder.show();
	}

	/**
	 * 打开浏览器
	 * 
	 * @param context
	 * @param url
	 */
	public static void openBrowser(Context context, String url) {
		try {
			Uri uri = Uri.parse(url);
			Intent it = new Intent(Intent.ACTION_VIEW, uri);
			context.startActivity(it);
		} catch (Exception e) {
			e.printStackTrace();
			ToastMessage(context, "无法浏览此网页", 500);
		}
	}

	
	/**
	 * 获取webviewClient对象
	 * 
	 * @return
	 */
	public static WebViewClient getWebViewClient() {
		return new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				openBrowser(view.getContext(), url);
				return true;
			}
		};
	}
	
	
	/**
	 * 网络没有连接界面
	 * 
	 * @param context
	 * @param title
	 * @param url
	 */
	public static void showNetworkError( final Activity context,View v,final Class cls) {
		UIHelper.ToastMessage(context, R.string.network_not_connected);
		//TODO 首页加载一张网络异常图片并添加点击刷新事件
		ImageView iv=new ImageView(context);
		iv.setBackgroundResource(R.drawable.network_error);
		((LinearLayout)v).addView(iv);
		iv.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(context, cls);
				context.startActivity(intent);
			}
		});
		
		return;
	}
	
	
	/**
	 * 调用系统安装了的应用分享
	 * 
	 * @param context
	 * @param title
	 * @param url
	 */
	public static void showShareMore(Activity context, final String title,
			final String url) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
		intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
		context.startActivity(Intent.createChooser(intent, "选择分享"));
	}

	/**
	 * 分享到'新浪微博'或'微信'的对话框
	 * 
	 * @param context
	 *            当前Activity
	 * @param title
	 *            分享的标题
	 * @param url
	 *            分享的链接
	 */
	public static void showShareDialog(final Activity context,
			final String title, final String url,final String imageUrl) {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setIcon(android.R.drawable.btn_star);
		builder.setTitle(context.getString(R.string.share));
		builder.setItems(R.array.app_share_items,
				new DialogInterface.OnClickListener() {
					//AccessInfo ac = AppConfig.readAccessToken(context, AppConfig.LOGIN_OAUTH_WEIBO);

					public void onClick(DialogInterface arg0, int arg1) {
						switch (arg1) {
						case 0:// 新浪微博
							ShareSDK.initSDK(context);
							OnekeyShare oks0 = new OnekeyShare();
							oks0.setSilent(false);
							oks0.setDialogMode();
							oks0.setText(title);
							//oks0.setImageUrl(imageUrl);
							
							//根据imageUrl获取本地图片地址
							final String filename = FileUtils.getFileName(imageUrl);
							String imagePath = context.getFilesDir() + File.separator+ filename;
							//oks0.setImagePath(imagePath);
							oks0.setPlatform(SinaWeibo.NAME);
							oks0.show(context);
							break;
						case 1:// 微信好友
							ShareSDK.initSDK(context);
							OnekeyShare oks1 = new OnekeyShare();
							oks1.setSilent(false);
							oks1.setDialogMode();
							oks1.setPlatform(SinaWeibo.NAME);
							oks1.setTitle("闪淘五湖四海 精选万里挑一 直邮千家万户 承诺假一赔十");
							oks1.setText(title);
							oks1.setUrl("http://www.taoyige.com");
							oks1.setImageUrl(imageUrl);
							oks1.setPlatform(Wechat.NAME);
							oks1.show(context);
							break;
						case 2:// 微信朋友圈
							WXFriendsHelper.shareToWXFriends(context, title, url);
							break;
						case 3:// QQ好友
							ShareSDK.initSDK(context);
							OnekeyShare oks3 = new OnekeyShare();
							oks3.setSilent(false);
							oks3.setDialogMode();
							oks3.setTitle("闪淘五湖四海 精选万里挑一 直邮千家万户 承诺假一赔十");
							oks3.setTitleUrl(url);
							oks3.setText(title+url);
							oks3.setImageUrl(imageUrl);
							oks3.setPlatform(QQ.NAME);
							oks3.show(context);
							break;
						case 4:// QQ空间
							ShareSDK.initSDK(context);
							OnekeyShare oks4 = new OnekeyShare();
							oks4.setSilent(false);
							oks4.setDialogMode();
							oks4.setImageUrl(imageUrl);
							oks4.setTitle("闪淘五湖四海 精选万里挑一 直邮千家万户 承诺假一赔十");
							oks4.setTitleUrl(url);
							oks4.setText(title);
							oks4.setSite("淘一个");
							oks4.setSiteUrl(url);
							oks4.setPlatform(QZone.NAME);
							oks4.show(context);
							break;
						case 5:// 短信
							ShareSDK.initSDK(context);
							OnekeyShare oks5 = new OnekeyShare();
							oks5.setSilent(false);
							oks5.setDialogMode();
							oks5.setText(title+"详情请访问www.taoyige.com");
							oks5.setPlatform(ShortMessage.NAME);
							oks5.show(context);
							break;
						case 6:// 邮件
							ShareSDK.initSDK(context);
							OnekeyShare oks6 = new OnekeyShare();
							oks6.setSilent(false);
							oks6.setDialogMode();
							oks6.setText(title+"\n详情请访问www.taoyige.com");
							oks6.setPlatform(Email.NAME);
							oks6.show(context);
							break;
						case 7:// 更多
							showShareMore(context, title, url);
							break;
						}
					}
				});
		builder.create().show();
	}
	

	
	/**
	 * 退出程序
	 * 
	 * @param cont
	 */
	public static void exit(final Context cont) {
		AlertDialog.Builder builder = new AlertDialog.Builder(cont);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setTitle(R.string.app_menu_surelogout);
		builder.setPositiveButton(R.string.sure,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 退出
						AppManager.getAppManager().appExit(cont);
					}
				});
		builder.setNegativeButton(R.string.cancle,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.show();
	}

}
